package com.hxd.mall.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.hxd.mall.R

class HxdStateFrameView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
    private var noNetwork: View? = null
    private var errorView: View? = null
    private var successView: View? = null
    var emptyView: View? = null
    lateinit var listener: OnReloadListener

    init {
        initView()//初始化View
    }

    private fun initView() {
        hideAll()
    }

    /**
     * 添加一个成功的View进来
     */
    fun bindSuccessView(view: View) {
        successView = view
        successView?.let {
            it.visibility = View.INVISIBLE//隐藏successView
            //将它添加进来
            addView(it)
        }
    }

    fun showSuccessView() {
        //先隐藏其他的
        hideAll()
        successView?.let {
            it.visibility = View.VISIBLE//隐藏successView
        }
    }

    fun showEmptyView() {
        //先隐藏其他的
        hideAll()
        emptyView = View.inflate(context, R.layout.widget_empty_data, null)
        addView(emptyView)
        emptyView?.visibility = View.VISIBLE
    }

    fun showErrorView() {
        //先隐藏其他的
        hideAll()
        errorView = View.inflate(context, R.layout.widget_network_error, null)
        val mLlReload = errorView?.findViewById<View>(R.id.widget_ll_network_error) as LinearLayout
        mLlReload.setOnClickListener { listener.onReload() }
        addView(errorView)
        errorView?.visibility = View.VISIBLE
    }

    fun showNoNetwork() {
        //先隐藏其他的
        hideAll()
        noNetwork = View.inflate(context, R.layout.widget_no_network, null)
        addView(noNetwork)
        noNetwork?.visibility = View.VISIBLE
    }

    /**
     * 隐藏所有的View
     */
    private fun hideAll() {
        //设置各界面不可见，同时让他们不重新layout，要用的时候直接show就行了
        noNetwork?.visibility = View.INVISIBLE
        errorView?.visibility = View.INVISIBLE
        emptyView?.visibility = View.INVISIBLE
        successView?.visibility = View.INVISIBLE
    }

    fun setOnReloadListener(listener: OnReloadListener) {
        this.listener = listener
    }

    interface OnReloadListener {
        /**
         * 当重新加载的按钮被点击的时候调用
         */
        fun onReload()
    }
}
